package com.glsc.ngateway.flowable.listener.demandmanagement;

import com.glsc.ngateway.common.api.flowable.dto.ParamEmailDto;
import com.glsc.ngateway.common.base.domain.mysql.flowable.FlowableEhrEmp;
import com.glsc.ngateway.flowable.service.FlowableEhrEmpService;
import com.glsc.ngateway.flowable.service.MailService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.task.service.delegate.DelegateTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class DemandManagementSignatureHandler implements TaskListener, ApplicationContextAware {

    private static final Logger logger = LoggerFactory.getLogger(DemandManagementArrangeHandler.class);


    @Autowired
    private RuntimeService runtimeService;

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext arg0) throws BeansException {
        applicationContext = arg0;
    }

    @Override
    public void notify(DelegateTask delegateTask) {

        try {
            logger.info("需求管理会签，发送通知邮件开始");
            MailService mailService = (MailService) applicationContext.getBean("mailService");
            FlowableEhrEmpService flowableEhrEmpService = (FlowableEhrEmpService) applicationContext.getBean("flowableEhrEmpService");
            FlowableEhrEmp emp = flowableEhrEmpService.getUserInfo(delegateTask.getAssignee());

            ParamEmailDto dto = new ParamEmailDto();
            dto.setContext(createHtmlContent());
            dto.setTitle("需求管理系统通知-待办事项");
            dto.setRecipient(emp.getEmail());
            mailService.sendEmail(dto);
            logger.info("需求管理会签，发送通知邮件结束");
        } catch (Exception e) {
            logger.error("DemandManagementSignatureHandler处理异常，结束处理。processid=" + delegateTask.getProcessInstanceId(), e);
            throw new RuntimeException("DemandManagementSignatureHandler处理异常，结束处理。processid=" + delegateTask.getProcessInstanceId(), e);
        }
    }


    private String createHtmlContent() {
        return "<html lang='en' style='margin: 0; padding: 0; font-family: Helvetica Neue, Microsoft Yahei, Hiragino Sans GB, WenQuanYi Micro Hei, sans-serif; font-size: 14px; text-align: center; word-break: normal; font-weight: normal;'>"
                + "<head>"
                + "<style type='text/css'>body {border-width:0;margin:0}img {border:0;margin:0;padding:0}</style><base target='_blank' />"
                + "</head>"
                + "<p>您好：</p>"
                + "<p>     需求管理有待办事项，烦请处理。    "
                + "<a href='http://zy.glsc.com.cn/gateway/realProjectMgr'>点击查看</a></p>"
                + "</html>";
    }

}